package com.gitee.easyopen.sdk.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import com.gitee.easyopen.sdk.UploadFile;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * post工具类
 * 
 * @author tanghc
 */
public class PostUtil {
    public static String UPLOAD_FORM_DATA_NAME = "body_data";
    public static final String CONTECT_TYPE_STREAM = "application/octet-stream";
    public static final MediaType STREAM = MediaType.parse(CONTECT_TYPE_STREAM);
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final MediaType TEXT = MediaType.parse("text/plain");

    private final static Map<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();

    private static OkHttpClient httpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
        public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
            cookieStore.put(httpUrl.host(), list);
        }

        public List<Cookie> loadForRequest(HttpUrl httpUrl) {
            List<Cookie> cookies = cookieStore.get(httpUrl.host());
            return cookies != null ? cookies : new ArrayList<Cookie>();
        }
    }).build();
    
    /**
     * get请求
     * @param url
     * @param header
     * @return
     * @throws IOException
     */
    public static String get(String url, Map<String, String> header) throws IOException {
        Builder builder = new Request.Builder().url(url).get();
        // 添加header
        addHeader(builder, header);

        Request request = builder.build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    /**
     * post提交json字符串
     * 
     * @param url
     * @param json
     * @return 返回响应内容
     * @throws IOException
     */
    public static String postJson(String url, String json) throws IOException {
        return postJson(url, json, null);
    }

    /**
     * post提交json字符串
     * 
     * @param url
     * @param json
     * @param header
     *            header内容
     * @return
     * @throws IOException
     */
    public static String postJson(String url, String json, Map<String, String> header) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Builder builder = new Request.Builder().url(url).post(body);
        // 添加header
        addHeader(builder, header);

        Request request = builder.build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 上传文件
     * 
     * @param url
     * @param formData
     * @param header
     * @param files
     * @return
     * @throws IOException
     */
    public static String postFile(String url, String json, Map<String, String> header, List<UploadFile> files)
            throws IOException {
        // 创建MultipartBody.Builder，用于添加请求的数据
        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder();
        bodyBuilder.setType(MultipartBody.FORM);
        
        for (UploadFile uploadFile : files) {
            bodyBuilder.addFormDataPart(uploadFile.getName(), // 请求的名字
                    uploadFile.getFileName(), // 文件的文字，服务器端用来解析的
                    RequestBody.create(null, uploadFile.getFileData()) // 创建RequestBody，把上传的文件放入
            );
        }
        
        bodyBuilder.addFormDataPart(UPLOAD_FORM_DATA_NAME, json);

        RequestBody requestBody = bodyBuilder.build();

        Builder builder = new Request.Builder().url(url).post(requestBody);

        // 添加header
        addHeader(builder, header);

        Request request = builder.build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    /**
     * post普通文本
     * 
     * @param url
     * @param text
     * @return
     * @throws IOException
     */
    public static String postText(String url, String text) throws IOException {
        RequestBody body = RequestBody.create(TEXT, text);
        Builder builder = new Request.Builder().url(url).post(body);
        Request request = builder.build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    public static String postString(String url, JSONObject param) throws IOException {
        return postText(url, param == null ? "" : param.toJSONString());
    }

    private static void addHeader(Builder builder, Map<String, String> header) {
        if (header != null) {
            Set<Entry<String, String>> entrySet = header.entrySet();
            for (Entry<String, String> entry : entrySet) {
                builder.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
    }
}
